/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import bo.PessoaBO;
import dao.PessoaDAO;
import entity.Pessoa;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Junior Oliveira
 */
public class CadPessoa extends javax.swing.JFrame {

    /**
     * Creates new form CadPessoa
     */
    private int opcao = 0;
    private int linha;

    public CadPessoa() throws SQLException {
        initComponents();
        bloquearCampos();
        dadosTabela();
        atualizaId();
        bloquearBotoes();
    }

    public void atualizaId() throws SQLException {
        PessoaDAO.genericSQL("select * from pessoa");
        PessoaDAO.genericResultset.first();

        jTid.setText(PessoaDAO.genericResultset.getString("id"));
        jTnome.setText(PessoaDAO.genericResultset.getString("nome"));
        jFtelefone.setText(PessoaDAO.genericResultset.getString("telefone"));

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTid = new javax.swing.JTextField();
        jTnome = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jFtelefone = new javax.swing.JFormattedTextField();
        jBnovo = new javax.swing.JButton();
        jBeditar = new javax.swing.JButton();
        jBexcluir = new javax.swing.JButton();
        jBsalvar = new javax.swing.JButton();
        jBcancelar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Tela de Cadastro");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadastro de contatos"));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Identificador");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Nome");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setText("Telefone");

        try {
            jFtelefone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        jBnovo.setText("Novo");
        jBnovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBnovoActionPerformed(evt);
            }
        });

        jBeditar.setText("Editar");
        jBeditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBeditarActionPerformed(evt);
            }
        });

        jBexcluir.setText("Excluir");
        jBexcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBexcluirActionPerformed(evt);
            }
        });

        jBsalvar.setText("Salvar");
        jBsalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBsalvarActionPerformed(evt);
            }
        });

        jBcancelar.setText("Cancelar");
        jBcancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBcancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jBnovo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBeditar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBexcluir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBsalvar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBcancelar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jFtelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)
                            .addComponent(jTid)
                            .addComponent(jLabel2)
                            .addComponent(jTnome)
                            .addComponent(jLabel3))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jBeditar, jBexcluir, jBnovo, jBsalvar});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jFtelefone, jTid, jTnome});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTnome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jFtelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBsalvar)
                    .addComponent(jBexcluir)
                    .addComponent(jBeditar)
                    .addComponent(jBnovo)
                    .addComponent(jBcancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jBeditar, jBexcluir, jBnovo, jBsalvar});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jFtelefone, jTid, jTnome});

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Id", "Nome", "Telefone"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setResizable(false);
            jTable1.getColumnModel().getColumn(1).setResizable(false);
            jTable1.getColumnModel().getColumn(2).setResizable(false);
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 509, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        setSize(new java.awt.Dimension(938, 289));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jBnovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBnovoActionPerformed
        opcao = 1;
        desbloquearCampos();
        limparCampos();
        bloquearBotoes2();
       
    }//GEN-LAST:event_jBnovoActionPerformed

    private void jBeditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBeditarActionPerformed
        opcao = 2;
        desbloquearCampos();
        bloquearBotoes2();
    }//GEN-LAST:event_jBeditarActionPerformed

    private void jBexcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBexcluirActionPerformed
        
        int opc = JOptionPane.showConfirmDialog(null, "Deseja excluir o contato '"+jTnome.getText()+"' ", "Excluir contato", JOptionPane.YES_NO_OPTION, 2);
        if(opc == JOptionPane.YES_OPTION){
            try {
                PessoaBO.delete(Integer.valueOf(jTid.getText()));
                 dadosTabela();
                JOptionPane.showMessageDialog(null, "Contato Excluido com sucesso!", "Excluir contato", 1);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Erro ao tentar deletar o registro!", "Erro!", 0);
            }
        }  
        
    }//GEN-LAST:event_jBexcluirActionPerformed

    private void jBsalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBsalvarActionPerformed
        if (opcao == 1) {
            try {
                salvar();
            } catch (Exception ex) {
                Logger.getLogger(CadPessoa.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (opcao == 2) {
            try {
                editar();
            } catch (Exception ex) {
                Logger.getLogger(CadPessoa.class.getName()).log(Level.SEVERE, null, ex);
            }
        } 
    }//GEN-LAST:event_jBsalvarActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        bloquearCampos();
         bloquearBotoes();
        linha = jTable1.getSelectedRow();

        jTid.setText(jTable1.getValueAt(linha, 0).toString());
        jTnome.setText(jTable1.getValueAt(linha, 1).toString());
        jFtelefone.setText(jTable1.getValueAt(linha, 2).toString());

    }//GEN-LAST:event_jTable1MouseClicked

    private void jBcancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBcancelarActionPerformed

        try {
            bloquearCampos();
            atualizaId();
            dadosTabela();
            bloquearBotoes();
        } catch (SQLException ex) {
            Logger.getLogger(CadPessoa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jBcancelarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CadPessoa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CadPessoa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CadPessoa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CadPessoa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new CadPessoa().setVisible(true);
                } catch (SQLException ex) {
                    Logger.getLogger(CadPessoa.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBcancelar;
    private javax.swing.JButton jBeditar;
    private javax.swing.JButton jBexcluir;
    private javax.swing.JButton jBnovo;
    private javax.swing.JButton jBsalvar;
    private javax.swing.JFormattedTextField jFtelefone;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTid;
    private javax.swing.JTextField jTnome;
    // End of variables declaration//GEN-END:variables

    public void limparCampos() {
        jTid.setText("ID automático");
        jTnome.setText(null);
        jFtelefone.setText(null);
    }

    public void bloquearCampos() {
        jTid.setEnabled(false);
        jTnome.setEnabled(false);
        jFtelefone.setEnabled(false);
    }

    public void desbloquearCampos() {
//        jTid.setEnabled(true);
        jTnome.setEnabled(true);
        jTnome.requestFocus();
        jFtelefone.setEnabled(true);
    }

    public void dadosTabela() throws SQLException {
        ArrayList<Pessoa> listaPessoas = PessoaBO.listAll();

        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();

        modelo.setNumRows(0);

        for (int i = 0; i < listaPessoas.size(); i++) {
            modelo.addRow(new Object[]{
                listaPessoas.get(i).getId(),
                listaPessoas.get(i).getNome(),
                listaPessoas.get(i).getTelefone()
            });
        }
    }

    public void salvar() throws Exception {
        if (jTnome.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Campo 'nome' está não pode ser vazio!", "Campo vazio", 2);
            jTnome.requestFocus();
        } else if (jFtelefone.getText().equals("(  )    -    ")) {
            JOptionPane.showMessageDialog(null, "Campo 'telefone' não pode ser vazio!", "Campo vazio", 2);
            jFtelefone.requestFocus();
        } else {
            try {
                Pessoa pessoaGui = new Pessoa();
                pessoaGui.setNome(jTnome.getText());
                pessoaGui.setTelefone(jFtelefone.getText());
                PessoaBO.save(pessoaGui);
                JOptionPane.showMessageDialog(null, "Contato salvo com sucesso!", "Salvo com sucesso", 1);
                bloquearCampos();
                dadosTabela();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Erro ao salvar o contato\n\n" + ex, "Erro", 0);
            }
        }
    }

    public void editar() throws Exception {
        if (jTnome.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Campo 'nome' está não pode ser vazio!", "Campo vazio", 2);
            jTnome.requestFocus();
        } else if (jFtelefone.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Campo 'telefone' não pode ser vazio!", "Campo vazio", 2);
            jFtelefone.requestFocus();
        } else {
            try {
                Pessoa pessoa = new Pessoa();
                pessoa.setId(Integer.parseInt(jTid.getText()));
                pessoa.setNome(jTnome.getText());
                pessoa.setTelefone(jFtelefone.getText());
                PessoaBO.update(pessoa);
                bloquearCampos();
                dadosTabela();
                JOptionPane.showMessageDialog(null, "Contato editado com sucesso!", "Editado com sucesso", 1);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "Erro ao salvar o contato\n\n" + ex, "Erro", 0);
            }
        }
    }
    public void bloquearBotoes(){
        jBeditar.setEnabled(true);
        jBexcluir.setEnabled(true);
        jBnovo.setEnabled(true);
        jBcancelar.setEnabled(false);
        jBsalvar.setEnabled(false);
      
    }
    public void bloquearBotoes2(){
        jBcancelar.setEnabled(true);
        jBeditar.setEnabled(false);
        jBexcluir.setEnabled(false);
        jBnovo.setEnabled(false);
        jBsalvar.setEnabled(true);
    }
}
